<script setup lang="tsx">
  import { NButton, NIcon, NPopconfirm, NTag } from 'naive-ui';
  import {
    fetchGetUserList,
    fetchPostAddUser,
    fetchPostDeleteUser,
    fetchPostUser,
  } from '@/service/api';
  import { $t } from '@/locales';
  import { useAppStore } from '@/store/modules/app';
  import {
    enableStatusRecord,
    roleStatusRecord,
    userGenderRecord,
  } from '@/constants/business';
  import { formatDate, handleCopy, isPermission } from '@/utils/tools';
  import { useTable, useTableOperate } from '@/hooks/common/table';
  import type { Api } from '@/typings/api';
  import UserOperateDrawer from './modules/user-operate-drawer.vue';
  import UserSearch from './modules/user-search.vue';
  const appStore = useAppStore();
  const {
    columns,
    columnChecks,
    data,
    getData,
    getDataByPage,
    loading,
    mobilePagination,
    searchParams,
    pagination,
    resetSearchParams,
  } = useTable({
    apiFn: fetchGetUserList,
    showTotal: true,
    apiParams: {
      pageNum: 1,
      pageSize: 10,
    },
    columns: () => [
      {
        type: 'selection',
        align: 'center',
        width: 48,
      },
      {
        key: 'index',
        title: $t('common.index'),
        align: 'center',
        width: 64,
      },
      {
        key: 'id',
        title: $t('page.userData.userList.id'),
        align: 'center',
        width: 150,
        render: (row: any) => {
          return (
            <>
              <span>{row.id}</span>
              {row.id && (
                <icon-local-copy
                  style="cursor: pointer;"
                  onClick={() => handleCopy(row.id)}
                />
              )}
            </>
          );
        },
      },
      {
        key: 'avatar',
        title: $t('page.userData.userList.avatar'),
        align: 'center',
        minWidth: 50,
        render: (row: any) => {
          return (
            <n-image
              width="50"
              src={row.avatar ?? 'https://dash.reecho.ai/logo.svg'}
            />
          );
        },
      },
      {
        key: 'name',
        title: $t('page.userData.userList.name'),
        align: 'center',
        minWidth: 50,
      },
      {
        key: 'phone',
        title: $t('page.userData.userList.phone'),
        align: 'center',
        minWidth: 100,
      },
      {
        key: 'role',
        title: $t('page.userData.userList.role'),
        align: 'center',
        width: 100,
        render: (row: any) => {
          const tagMap: Record<Api.User.roleStatus, NaiveUI.ThemeColor> = {
            admin: 'success',
            user: 'warning',
            super: 'primary',
            enterprise: 'info',
          };

          const label = $t(roleStatusRecord[row.role as Api.User.roleStatus]);

          return (
            <NTag type={tagMap[row.role as Api.User.roleStatus]}>{label}</NTag>
          );
        },
      },
      {
        key: 'sex',
        title: $t('page.manage.user.userGender'),
        align: 'center',
        width: 50,
        render: (row: any) => {
          const tagMap: Record<
            Api.SystemManage.UserGender,
            NaiveUI.ThemeColor
          > = {
            '0': 'error',
            '1': 'primary',
          };

          const label = $t(
            userGenderRecord[row.sex as Api.SystemManage.UserGender]
          );

          return (
            <NTag type={tagMap[row.sex as Api.SystemManage.UserGender]}>
              {label}
            </NTag>
          );
        },
      },
      {
        key: 'age',
        title: $t('page.manage.user.age'),
        align: 'center',
        minWidth: 50,
        sorter: true,
      },

      {
        key: 'orderId',
        title: $t('page.manage.user.orderId'),
        align: 'center',
        minWidth: 50,
      },
      {
        key: 'email',
        title: $t('page.userData.userList.email'),
        align: 'center',
        width: 100,
      },
      {
        key: 'address',
        title: $t('page.manage.user.address'),
        align: 'center',
        width: 150,
      },
      {
        key: 'text',
        title: $t('page.manage.user.text'),
        align: 'center',
        width: 200,
      },
      {
        key: 'createdAt',
        title: $t('page.userData.userList.createdAt'),
        align: 'center',
        minWidth: 100,
        render: (row: any) => {
          return formatDate(row.createdAt, 'YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        key: 'updatedAt',
        title: $t('page.userData.userList.updatedAt'),
        align: 'center',
        minWidth: 100,
        render: (row: any) => {
          return formatDate(row.updatedAt, 'YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        key: 'deletedAt',
        title: $t('page.userData.userList.deletedAt'),
        align: 'center',
        minWidth: 100,
        render: (row: any) => {
          return formatDate(row.deletedAt, 'YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        key: 'operate',
        title: $t('common.operate'),
        align: 'center',
        width: 130,
        render: (row: any) => (
          <div class="flex-center gap-8px">
            {/* <NButton type="warning"  ghost size="small" onClick={() => details(row.id)}>
            {$t('common.details')}
          </NButton> */}

            {!row.deletedAt ? (
              <NButton
                type="primary"
                ghost
                size="small"
                onClick={() => edit(row.id)}
              >
                {$t('common.edit')}
              </NButton>
            ) : (
              ''
            )}
            {!row.deletedAt ? (
              <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
                {{
                  default: () => $t('common.confirmDelete'),
                  trigger: () => (
                    <NButton type="error" ghost size="small">
                      {$t('common.delete')}
                    </NButton>
                  ),
                }}
              </NPopconfirm>
            ) : (
              ''
            )}
          </div>
        ),
      },
    ],
  });

  const {
    drawerVisible,
    operateType,
    editingData,
    handleAdd,
    handleEdit,
    handleDetails,
    checkedRowKeys,
    onBatchDeleted,
    onDeleted,
    // closeDrawer
  } = useTableOperate(data, getData);

  async function handleBatchDelete() {
    // request

    onBatchDeleted();
  }

  async function handleDelete(id: number) {
    // request
    const a = await fetchPostDeleteUser({ id });
    console.log('a', a);

    onDeleted();
  }

  function edit(id: number) {
    handleEdit(id);
  }

  function details(id: number) {
    handleDetails(id);
  }
  // 数据提交
  const postUserData = async (data: any, type: string) => {
    console.log('准备提交的数据data', data);

    if (type === 'add') {
      const res = await fetchPostAddUser(data);
      getDataByPage();
    } else {
      const res = await fetchPostUser(data);
      getDataByPage(pagination.page);
    }
  };
  // 重置筛选
  const resetSearch = () => {
    searchParams.name = '';
    searchParams.email = '';
    searchParams.phone = '';
    searchParams.id = '';
    searchParams.orderId = '';
    searchParams.sex = '';
  };
  const handleSorterChange = (newSorter: any) => {
    // columnKey: 'credit', sorter: true, order: 'descend|ascend| false
    if (newSorter.order !== false) {
      searchParams.columnKey = newSorter.columnKey;
      searchParams.order = newSorter.order.slice(0, -3);
    } else {
      delete searchParams.columnKey;
      delete searchParams.order;
    }
    getDataByPage();
  };
</script>

<template>
  <div
    class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto"
  >
    <UserSearch
      v-model:model="searchParams"
      @reset="resetSearch"
      @search="getDataByPage"
    />
    <NCard
      :title="$t('page.userData.userList.title')"
      :bordered="false"
      size="small"
      class="sm:flex-1-hidden card-wrapper"
    >
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          is-operate
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="962"
        :loading="loading"
        remote
        :row-key="(row: any) => row.id"
        :pagination="mobilePagination"
        class="sm:h-full"
        @update:sorter="handleSorterChange"
      />
      <UserOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="postUserData"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
